/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package concurrent.queue;

import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author harker777
 */
class Consumer implements Runnable {

	@Override
	public void run() {
		Random random = new Random();
		String name = Thread.currentThread().getName();
		while (true) {
			synchronized (CommonDataStorage.class) {
				System.out.println(name + " starting to work:");
				Boolean dataHasPlace = findPlace();

				if (dataHasPlace) {
					consume();
					CommonDataStorage.class.notify();
				} else {
					try {
						System.out.println("Nothing to consume");
						CommonDataStorage.class.wait();
					} catch (InterruptedException ex) {
					}
				}
			}
			try {
				Integer sleepTime = (Integer) (random.nextInt(CommonDataStorage.getConsumerMaxWaitTime()));
				Thread.sleep(sleepTime);
			} catch (InterruptedException ex) {
				Logger.getLogger(ProducerConsumerDemo.class.getName()).log(Level.SEVERE, null, ex);
			}
		}
	}

	private Boolean findPlace() {
		Integer candidate = 0;
		if (CommonDataStorage.getCurrentConsuming() == CommonDataStorage.getQueueSize() - 1) {
			candidate = 0;
		} else {
			candidate = CommonDataStorage.getCurrentConsuming() + 1;
		}
		if (CommonDataStorage.getData()[candidate] != 0) {
			CommonDataStorage.setCurrentConsuming(candidate);
			return true;
		} else {
			return false;
		}
	}

	private void consume() {
		Integer currentConsuming = CommonDataStorage.getCurrentConsuming();
		Integer currentNumber = CommonDataStorage.getCurrentNumber();
		int[] data = CommonDataStorage.getData();
		System.out.println("Consumed item " + data[currentConsuming] + " from slot #" + currentConsuming);
		data[currentConsuming] = 0;
		ProducerConsumerDemoUtils.print(data);
		CommonDataStorage.setCurrentNumber(currentNumber - 1);
	}
}